<template>
    <div>
        <h3>文章情感分析</h3>
        <el-input
            v-model="customPrompt"
            type="textarea"
            autosize
            :rows="3"
            placeholder="请输入你的提示词，例如：'请从积极、消极、中性三个维度分析这篇文章'"
        />
        <el-button @click="analyzeSentiment" type="primary" :loading="isLoadingAI" style="margin-top: 20px;">进行情感分析</el-button>
        <div v-if="displayText" v-html="formatText(displayText)"></div>
        <p v-else>请点击按钮进行情感分析</p>
    </div>
</template>

<script setup>
import {ref, defineProps} from 'vue';
import {Ollama} from '@langchain/ollama';
import {OLLAMAURL, OLLAMAURL_MODEL_NAME} from "@/assets/js/location.js";
import MarkdownIt from 'markdown-it';
const isLoadingAI=ref(false)
const props = defineProps({
    articleContent: {
        type: String,
        default: ''
    }
});

const sentimentResult = ref('');
const displayText = ref('');
const md = new MarkdownIt({
    html: true, // 允许解析原始 HTML 标签
    breaks: true // 可选：保留换行符
});

const customPrompt = ref('');

const formatText = (text) => {
    const html = md.render(text);
    // 使用正则替换并添加样式
    return html.replace(
        /<think>(.*?)<\/think>/gis,
        (match, p1) => `
            <div style="color: #7f7f7f; margin: 8px 0; padding-left: 12px; border-left: 3px solid #e2e8f0;">
                <span style="font-style: italic;">已深度思考：</span>
                ${p1}
            </div>
        `
    );
};

const analyzeSentiment = async () => {
    try {
        isLoadingAI.value=true
        displayText.value=""
        const ollama = new Ollama({
            baseUrl: OLLAMAURL,
            model: OLLAMAURL_MODEL_NAME,
        });
        const prompt = `${customPrompt.value ? `${customPrompt.value}\n\n以下是文章内容：\n` : '请对以下文章进行情感分析：\n'}${props.articleContent}        `.trim();
        const response = await ollama.stream([prompt]);

        async function streamReply() {
            for await (let chunk of response) {
                displayText.value += chunk
            }
            isLoadingAI.value=false
        }
        await streamReply();
    } catch (error) {
        console.error('情感分析出错:', error);
        sentimentResult.value = '情感分析出错，请稍后重试。';
    }
};
</script>

<style scoped>
/* 可以添加一些样式 */
</style>